﻿@model string
@{
    ViewBag.Title = "Text File Editor";
    Layout = ViewBag.Layout;
}
@if (ViewBag.IsIframe)
{
    <script src="@Url.Content("~/Scripts/jquery-1.9.1.min.js")"></script>
    <script src="@Url.Content("~/Scripts/jquery-ui-1.9.1.js")"></script>
}

<div class="BatchFileUploadPage">
    <link href="@Url.Content("~/Content/CodeMirror/codemirror.css")" rel="stylesheet" />
    <link href="@Url.Content("~/Content/CodeMirror/foldgutter.css")" rel="stylesheet" />
    <link href="@Url.Content("~/Content/CodeMirror/show-hint.css")" rel="stylesheet" />
    <link href="@Url.Content("~/Content/bootstrap.min.css")" rel="stylesheet" />

    <script src="@Url.Content("~/Scripts/bootstrap.min.js")"></script>
    <script src="@Url.Content("~/Scripts/CodeMirror/codemirror.js")"></script>
    <script src="@Url.Content("~/Scripts/CodeMirror/foldcode.js")"></script>
    <script src="@Url.Content("~/Scripts/CodeMirror/foldgutter.js")"></script>
    <script src="@Url.Content("~/Scripts/CodeMirror/brace-fold.js")"></script>
    <script src="@Url.Content("~/Scripts/CodeMirror/xml-fold.js")"></script>
    <script src="@Url.Content("~/Scripts/CodeMirror/markdown-fold.js")"></script>
    <script src="@Url.Content("~/Scripts/CodeMirror/comment-fold.js")"></script>
    <script src="@Url.Content("~/Scripts/CodeMirror/show-hint.js")"></script>
    <script src="@Url.Content("~/Scripts/CodeMirror/xml-hint.js")"></script>
    <script src="@Url.Content("~/Scripts/CodeMirror/xml.js")"></script>
    <script src="@Url.Content("~/Scripts/CodeMirror/matchtags.js")"></script>
    <script src="@Url.Content("~/Scripts/CodeMirror/markdown.js")"></script>
    <script src="@Url.Content("~/Scripts/CodeMirror/searchwithoutdialog.js")"></script>
    <script src="@Url.Content("~/Scripts/CodeMirror/searchcursor.js")"></script>
    
    <link href="@Url.Content("~/Content/jquery.fileupload-ui.css")" rel="stylesheet" />
    <link href="@Url.Content("~/Content/jquery.fileupload.css")" rel="stylesheet" />
    
    <script src="@Url.Content("~/Scripts/jquery.ui.widget.js")"></script>
    <script src="@Url.Content("~/Scripts/jquery.fileupload.js")"></script>
    <script src="@Url.Content("~/Scripts/jquery.fileupload-ui.js")"></script>
    <script src="@Url.Content("~/Scripts/jquery.iframe-transport.js")"></script>

    <script src="@Url.Content("~/Scripts/PrettyTextDiff/jquery.pretty.text.diff.min.js")"></script>
    <script src="@Url.Content("~/Scripts/PrettyTextDiff/jquery.diff.match.patch.js")"></script>

    <script src="@Url.Content("~/Scripts/pdfobject_source.js")"></script>
    <script type="text/javascript">
        window.onload = function () {
            var success = new PDFObject({ url: "/Pdfs/sample.pdf" }).embed("pdf");
        };
    </script>
    <style type="text/css">
        /*this is for the pretty text diff*/
        ins {
            background-color: #c6ffc6;
            text-decoration: none;
        }
        del {
            background-color: #ffc6c6;
        }
        .hide{ visibility: hidden }
        .overflow{
            padding: 0px 0px 0px 0px;
            margin: 0px 0px 0px 0px;
            white-space: pre;
            overflow: auto;
            border: solid 1px;
            height: 100%;
            width: 49%;
        }
        .diff {
            border: 1px solid green;
        }
        textarea { 
            font-family: Calibri, Tahoma, Arial, Helvetica, Sans-Serif;
            color: #232323;
            font-size: 1em;
            height: 100%;
            width: 49%;
        }
        .CodeMirror {
            font-family: Calibri, Tahoma, Arial, Helvetica, Sans-Serif;
            border: 1px solid gray;
            font-size: 1em;            
            height: 100%;
            width: 49%;
            float: left;
        }
        .pdf {
            font-family: Calibri, Tahoma, Arial, Helvetica, Sans-Serif;
            border: 1px solid gray;
            font-size: 1em;            
            height: 100%;
            width: 49%;
            float: left;
            margin-left: 5px;
        }
        .bar {
            height: 18px;
            background: green;
        }
    </style>
    <script>
        $(document).ready(function () {
            function foldByNodeOrder(node) {
                // 0 - fold all
                unfoldAll();
                node++;
                for (var l = editor.firstLine() ; l <= editor.lastLine() ; ++l)
                    if (node == 0)
                        editor.foldCode({ line: l, ch: 0 }, null, "fold");
                    else node--;
            }

            function foldByLevel(level) {
                foldByNodeOrder(0);
                // initialize vars
                var cursor = editor.getCursor();
                cursor.ch = 0;
                cursor.line = 0;
                var range = editor.getViewport();
                foldByLevelRec(cursor, range, level);
                return false;
            }

            function unfoldAll() {
                for (var i = 0; i < editor.lineCount() ; i++) {
                    editor.foldCode({ line: i, ch: 0 }, null, "unfold");
                }
            }

            function foldByLevelRec(cursor, range, level) {
                if (level > 0) {
                    var searcher = editor.getSearchCursor("<", cursor, false);
                    while (searcher.findNext() && searcher.pos.from.line < range.to) {
                        // unfold the tag
                        editor.foldCode(searcher.pos.from, null, "unfold");
                        // move the cursor into the tag
                        cursor = searcher.pos.from;
                        cursor.ch = searcher.pos.from.ch + 1;
                        // find the closing tag
                        var match = CodeMirror.findMatchingTag(editor, cursor, range);
                        if (match) {
                            if (match.close) {
                                // create the inner-range and jump the searcher after the ending tag
                                var innerrange = { from: range.from, to: range.to };
                                innerrange.from = cursor.line + 1;
                                innerrange.to = match.close.to.line;
                                // the recursive call
                                foldByLevelRec(cursor, innerrange, level - 1);
                            }
                            // move to the next element in the same tag of this function scope
                            var nextcursor = { line: cursor.line, to: cursor.ch };
                            if (match.close) {
                                nextcursor.line = match.close.to.line;
                            }
                            nextcursor.ch = 0;
                            nextcursor.line = nextcursor.line + 1;
                            searcher = editor.getSearchCursor("<", nextcursor, false);
                        }
                    }
                }
            }

            var editor = CodeMirror.fromTextArea(document.getElementById("ChangedFileText"), {
                mode: "xml",
                lineNumbers: true,
                extraKeys: {
                    "Ctrl-J": "toMatchingTag",
                    "Ctrl-Q": function (cm) { cm.foldCode(cm.getCursor()); },
                    "Ctrl-0": function () { unfoldAll(); },
                    "Alt-0": function () { foldByLevel(0); },
                    "Alt-1": function () { foldByLevel(1); },
                    "Alt-2": function () { foldByLevel(2); },
                    "Alt-3": function () { foldByLevel(3); },
                    "Alt-4": function () { foldByLevel(4); },
                    "Alt-5": function () { foldByLevel(5); },
                    "Alt-6": function () { foldByLevel(6); },
                    "Alt-7": function () { foldByLevel(7); },
                    "Alt-8": function () { foldByLevel(8); },
                    "Alt-9": function () { foldByLevel(9); },
                },
                foldGutter: true,
                matchTags: { bothTags: true },
                gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"]
            });


            var uploadfileId;
            var fileId = $('#fileId').val();
            var fileType = $('#fileType').val();

            var getFileFromServerUrl = '@Url.Action("DownloadFileAsText", "Files")';

            function getFileFromServer(fileId, fileType) {
                $.get(getFileFromServerUrl + "/" + fileId + "?type=" + fileType, function (data) {
                        setInitDowloadText(data);
                    })
                    .fail(function (data) {
                        showApprovedMessage('danger', 'Error: Failed to get file from server', null);
                    });
            }

            var verifyFileWithoutSavingUrl = '@Url.Action("VerifyFileWithoutSaving", "Files")';
            if (notmsieversion()) {
                $('#fileupload').fileupload({
                    autoUpload: true,
                    url: verifyFileWithoutSavingUrl + "/" + fileId + "?type=" + fileType,
                    dataType: 'json',
                    acceptFileTypes: /(\.|\/)(xml)$/i,
                    maxFileSize: 5000000, // 5 MB
                    maxNumberOfFiles: 1,
                    add: function (e, data) {
                        showApprovedMessage('info', 'Upload and verifying, please wait...', null);
                        $('#progress .bar').css('width', 0 + '%');
                        data.submit();
                    },
                    done: function (e, data) {
                        var response = $.parseJSON(data.response().jqXHR.responseText);
                        if (response.isVerified) {
                            showApprovedMessage('warning', 'File was not saved!, review differences and save', null);
                        } else {
                            showApprovedMessage('danger', 'Error: ' + response.message, response.validationErrors);
                        }
                        setVerifyText(response.content);
                    },
                    progressall: function (e, data) {
                        var maxwidth = $(document).width() - 40;
                        var progress = parseInt(data.loaded / data.total * maxwidth, 10);
                        $('#progress .bar').css(
                            'width',
                            progress + 'px'
                        );
                    },
                    error: function (data, status, errorThrown) {
                        var response = $.parseJSON(data.response().jqXHR.responseText);
                        showApprovedMessage('danger', 'Error: ' + status + ',' + errorThrown + ',' + response.message, null);
                        setVerifyText(response.content);
                    }
                });
            } else {
                $('#fileupload').click(function () {
                    showApprovedMessage('danger', 'This feature does not work with internet explorer versions 9 and under, you can still edit and save it online (or copy-past)', null);
                    return false;
                });
            }

            var saveTextToFileUrl = '@Url.Action("SaveTextToFile", "Files")';
            function saveTextToFile(name, content) {
                var model =
                {
                    "Name": name,
                    "Content": content,
                };
                $.ajax({
                    url: saveTextToFileUrl + "/" + fileId + "?type=" + fileType,
                    type: 'POST',
                    dataType: 'json',
                    data: JSON.stringify(model),
                    contentType: 'application/json; charset=utf-8',
                    success: function (data, status) {
                        if (data.isUploaded) {
                            showApprovedMessage('info-delay', data.message, null);
                        }
                        else {
                            showApprovedMessage('danger', data.message, data.validationErrors);
                        }
                        setSavedText(content, data.isUploaded);
                    },
                    error: function (data, status, errorThrown) {
                        showApprovedMessage('danger', 'Error: ' + status + ',' + errorThrown + ',' + data.message, null);
                        setSavedText(content, false);
                    }
                });
                return false;
            }

            function setInitDowloadText(text) {
                $("#OriginalFileText").val(text);
                $("#ChangedFileText").val(text);
                editor.setOption("readOnly", true);
                editor.setValue(text);
            }

            function setVerifyText(text) {
                $("#ChangedFileTextTd").text(text);
                $("#ChangedFileText").val(text);
                showEdit();
                editor.setValue(text);
                showDiff();
            }

            function setSavedText(text, isUploaded) {
                $("#ChangedFileTextTd").text(text);
                if (isUploaded) {
                    $("#OriginalFileTextTd").text(text);
                    $("#OriginalFileText").val(text);
                    showEdit();
                    editor.setValue(text);
                }
            }

            function showDiff() {
                $('#editBtn').prop('disabled', false);
                $('#diffBtn').prop('disabled', true);
                $('#progress .bar').css('width', 0 + '%');
                editor.save();
                // move text from textarea to div's
                $("#ChangedFileTextTd").text($('#ChangedFileText').val());
                $("#OriginalFileTextTd").text($('#OriginalFileText').val());
                // show diff div
                $("#wrapper").prettyTextDiff({
                    cleanup: $("#cleanup").is(":checked")
                });
                $('#wrapperDiv').hide();
                $('#wrapper').show();
            }

            function showEdit() {
                //$('#fileuploadspan').removeClass('disabled');
                //$('#fileupload').prop('disabled', false);
                $('#editBtn').prop('disabled', true);
                $('#diffBtn').prop('disabled', false);
                $('#saveBtn').prop('disabled', false);
                $('#progress .bar').css('width', 0 + '%');
                $('#wrapper').hide();
                $('#wrapperDiv').show();
                $('#ChangedFileText').attr("disabled", false);

                editor.setOption("readOnly", false);
            }

            $("#uploadBtn").click(function () {
                uploadfileId = $(this).val().split('/').pop().split('\\').pop();
                $('#progress .bar').css('width', 0 + '%');
                $('#fileupload').click();
                return false;
            });

            $("#editBtn").click(function () {
                showEdit();
                return false;
            });

            $("#diffBtn").click(function () {
                showDiff();
                return false;
            });

            $("#saveBtn").click(function () {
                $('#progress .bar').css('width', 0 + '%');
                //upload
                editor.save();
                saveTextToFile($('#fileId').val(), $('#ChangedFileText').val());
                return false;
            });

            function showApprovedMessage(type, msg, errors) {
                $('.ApprovalMessage').hide();

                if (errors != null) {
                    msg += '<br/>';
                    $.each(errors, function (index, value) { msg += value + '<br/>'; });
                    $('#ApprovalMessageText').after('<div style="clear:both;"></div>');
                }

                $('#ApprovalMessageText').html(msg);
                var approvalMessage = $('.ApprovalMessage');
                //reset
                approvalMessage.removeClass('alert-confirm').removeClass('alert-danger').removeClass('alert-info');
                $('#ApprovalMessageYes').hide(); $('#ApprovalMessageNo').hide(); $('#ApprovalMessageOk').hide();

                //act
                switch (type) {
                case 'info':
                    approvalMessage.addClass('alert-info').fadeIn('fast').fadeOut();
                    break;
                case 'info-delay':
                    approvalMessage.addClass('alert-info').fadeIn('fast').delay(3000).fadeOut();
                    break;
                case 'confirm':
                    $('#ApprovalMessageYes').show(); $('#ApprovalMessageNo').show();
                    $('.ApprovalMessage').addClass('alert-confirm').fadeIn('fast');
                    break;
                case 'warning':
                    $('#ApprovalMessageOk').show();
                    $('.ApprovalMessage').addClass('alert-confirm').fadeIn('fast');
                    break;
                case 'danger':
                    $('#ApprovalMessageOk').show();
                    $('.ApprovalMessage').addClass('alert-danger').fadeIn('fast');
                    break;
                }
                return false;
            }

            function hideApprovedMessage() {
                $('.ApprovalMessage').fadeOut();
                return false;
            }

            $('#ApprovalMessageOk').click(function (event) {
                $('.ApprovalMessage').fadeOut();
                return false;
            });

            function notmsieversion() {
                var ua = window.navigator.userAgent;
                var msie = ua.indexOf("MSIE ");

                var ver;
                if (msie > 0)
                    ver = (parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
                else
                    return true;

                if (ver < 10)
                    return false;
                else
                    return true;
            }

            getFileFromServer(fileId, fileType);
        });
    </script>    
    <div id="content" style="margin: 5px 5px 5px 5px;">
        <div id="InputIdDiv" style="display: none;">
            <input type="text" name="fileId" id="fileId" value="@ViewBag.FileId" />
            <input type="text" name="fileType" id="fileType" value="@ViewBag.FileType"/>
            <input id="cleanup" type="checkbox" value="true" checked="checked" />
        </div>
        <div id="ApprovalMessage" class="alert alert-info ApprovalMessage FullWidthMessage ui-helper-hidden" style="display: none;margin-right: 30px;min-height: 20px">
            <div style="float:left;"><i class="icon icon-info-sign"></i></div>
            <div id="ApprovalMessageBody" style="float:left;">
                <div id="ApprovalMessageText" style="float:left;"></div> 
                <div style="float:left;padding-left: 5px;">
                    <button id="ApprovalMessageYes" style="display: none;font-size: 9px;" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-primary" role="button"><span class="ui-button-icon-primary ui-icon ui-icon-check"></span><span class="ui-button-text">Yes</span></button>
                    <button id="ApprovalMessageNo" style="display: none;font-size: 9px;" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-primary" role="button"><span class="ui-button-icon-primary ui-icon ui-icon-close"></span><span class="ui-button-text">No</span></button>
                    <button id="ApprovalMessageOk" style="display: none;font-size: 9px;" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button"><span class="ui-button-text">OK</span></button>
                </div>
            </div>
        </div>
        <div id="ControlDiv" style="padding-left: 10px;padding-top: 1px;">
            @if (true)
            {
                <input id="editBtn" type='button' class='btn btn-primary' value='Edit' />
                <input id="diffBtn" type='button' class='btn btn-primary' value='View Changes' disabled/>
                <input id="saveBtn" type='button' class='btn btn-primary' value='Save' disabled/>
                <span id="fileuploadspan" class="btn btn-success fileinput-button" style="margin-left: 25px;">
                    <span>Upload</span>
                    <input id="fileupload" type="file" name="files[]" multiple />
                </span>
            }
        </div>
        <div style="clear:both;"></div>
        <div id="MessageBarDiv" style="padding-top: 5px;padding-left: 10px;">
            @if (true)
            {
                @:Read only mode, Click edit to change text.
            }
            else
            {
                @:Read only mode.
            }
            <div id="Functionality" style="padding-top: 5px;padding-left: 10px;">
            Ctrl-J: Jump to matching tag;
            Ctrl-Q: Collapse\Uncollapse tag;
            Ctrl-0: Uncollapse all;
            Alt-(0 to 9): Collapse from tag (0 - Collapse all);
            </div>
        </div>
        <div style="clear:both;"></div>
        <div id="ProgressBarDiv" style="padding-top: 5px;">
            <div id="progress">
                <div class="bar" style="width: 0%;"></div>
            </div>
        </div>
        <div style="clear:both;"></div>
        <div id="TextDiv">
            <div id="wrapper" style="display: none;">
                <div class="original hide" id="OriginalFileTextTd" style="display: none"></div>
                <div class="changed hide" id="ChangedFileTextTd" style="display: none"></div>
                <div class="diff overflow" id="DiffText"></div>
            </div>
            <div id="wrapperDiv">
                <div><textarea id="ChangedFileText" name="ChangedFileText" wrap="off" disabled></textarea></div>
                <div><textarea id="OriginalFileText" name="OriginalFileText" wrap="off" disabled style="display: none">@Model</textarea></div>
            </div>
            <div id="pdfDiv">
                <div id="pdf" class="pdf">It appears you don't have Adobe Reader or PDF support in this web browser. <a href="/pdf/sample.pdf">Click here to download the PDF</a></div>
            </div>
        </div>
        <div style="clear:both;"></div>
    </div>
</div>